package com.example.permission.common.utils;

import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;

/**
 * poi excel导入导出
 *
 * @author xuwenqian
 * @date 2021/9/16 16:59
 */
public class ExcelHutoolUtil {

    private static final Logger logger = LogManager.getLogger(ExcelHutoolUtil.class);
    private static final String[] XLS_XLSX_CSV = {"xls", "xlsx", "csv"};

    /**
     * excel导出（支持大批量数据，100w数据，30s左右）
     *
     * @param response  响应
     * @param fileName  文件名称
     * @param titleList 标题列表
     * @param fieldList 字段列表
     * @param dataList  传入数据
     * @author mozhu
     * @date 2021-09-18 16:17:04
     */
    public static void exportExcel(HttpServletResponse response, String fileName, List<String> titleList, List<String> fieldList, List<?> dataList) {
        try {
            ExcelWriter writer = ExcelUtil.getBigWriter();
            String[] titles = titleList.toArray(new String[titleList.size()]);
            String[] fields = fieldList.toArray(new String[titleList.size()]);
            for (int i = 0; i < titles.length; i++) {
                writer.addHeaderAlias(fields[i], titles[i]);
                writer.setColumnWidth(i, 20);
            }
            writer.setOnlyAlias(true);
            writer.write(dataList, true);
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8") + ".xlsx");
            writer.flush(response.getOutputStream(), true);
            writer.close();
            IoUtil.close(response.getOutputStream());
        } catch (IOException e) {
            logger.error("导出excel失败：{}", e.getMessage());
        }
    }

    /**
     * 读取excel
     * 性能一般,如需要大批量读取导入，自行实现使用ExcelUtil.readBySax();
     *
     * @param multipartFile 导入文件
     * @param tClass        返回实体类 @Alias("")注解对应别名
     * @param ignoreRows    忽略标题行，0开始
     * @return {@link List<T> }
     * @author mozhu
     * @date 2021-09-22 10:28:56
     */
    public static <T> List<T> readExcel(MultipartFile multipartFile, Class<T> tClass, int ignoreRows) {
        try {
            String fileName = multipartFile.getOriginalFilename().toLowerCase();
            // 获取Excel后缀名
            String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
            if (!Arrays.asList(XLS_XLSX_CSV).contains(fileType)) {
                return null;
            }
            ExcelReader reader = ExcelUtil.getReader(multipartFile.getInputStream());
            return reader.read(ignoreRows, 1, tClass);
        } catch (IOException e) {
            logger.error("导入excel失败：{}", e.getMessage());
            return null;
        }
    }

}
